﻿using Grow.Module.Service;
using Grow.Utils.Exceptions;
using System.Collections.Concurrent;

namespace Grow.AspNetCore.Service
{
    public class ServiceManager : IServiceManager
    {
        private readonly ConcurrentDictionary<Type, object?> _services;
        public ServiceManager()
        {
            _services = new();
        }


        public TService GetRequiredService<TService>() where TService : notnull
        {
            TService? service = GetService<TService>();
            return service is not null ? service : throw new GrowCheckException($"类型为“{typeof(TService).FullName}”的服务无法找到");
        }

        public TService? GetService<TService>() where TService : notnull
        {
            Type serviceType = typeof(TService);
            if (_services.TryGetValue(serviceType, out object? service))
            {
                if (service is TService tService)
                {
                    return tService;
                }
            }
            return default;
        }


        public void AddService<TService>(TService service) where TService : notnull
        {
            Type tServiceType = typeof(TService);
            _ = _services.AddOrUpdate(tServiceType, _ => service, (_, _) => service);
        }
    }
}
